package com.augmentum.login.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.augmentum.login.Constants;
import com.augmentum.login.dao.UserDao;
import com.augmentum.login.exception.ParamException;
import com.augmentum.login.exception.ServiceException;
import com.augmentum.login.model.Page;
import com.augmentum.login.model.User;
import com.augmentum.login.service.UserService;
import com.augmentum.login.util.StringUtil;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public User getUser(String userName, String password) throws ParamException, ServiceException {

        ParamException paramException = new ParamException();
        if (StringUtil.isEmpty(userName)) {
            paramException.addExceptionField(Constants.USER_NAME, Constants.USER_EMPTY);
        }

        if (StringUtil.isEmpty(password)) {
            paramException.addExceptionField(Constants.PASSWORD, Constants.PASSWORD_EMPTY);
        }

        if (paramException.hasExceptionFiled()) {
            throw paramException;
        }

        User user = userDao.getByName(userName);
        if (user == null) {
            throw new ServiceException(1, Constants.USER_ERROR);
        } else if (!user.getPassword().equals(password)) {
            throw new ServiceException(2, Constants.PASSWORD_ERROR);
        }
        return user;
    }

    @Override
    public void modifyPassword(int id, String name) {
        userDao.upatePassword(id, name);
    }

    @Override
    public void create(User user) {
        userDao.save(user);
    }

    @Override
    public void modifyUser(User user) {
        userDao.upate(user);
    }

    @Override
    public List<User> getAllUsers() {
        return userDao.findAll();
    }

    @Override
    public List<User> findListBYpage(String name, String role, Page page) {
        return userDao.findBYpage(name, role, page);
    }

    @Override
    public void deleteUserForBatch(String idsStr, String type) {
        userDao.deleteBatch(idsStr.replaceAll(" ", "").split(type));
    }

    @Override
    public User getUserByName(String name) {
        if(StringUtil.isEmpty(name)) {
            return null;
        }
        return userDao.getByName(name);
    }
}
